<template>
  <div class="chat-container" style="margin-top:30px;padding-left:10px;padding-right:10px">
    <!-- 聊天主界面 -->
    <div class="chat-wrapper">
      <!-- 聊天记录区域 -->
      <div class="chat-messages" style="height: calc(70vh - 100px); overflow-y: auto; padding: 15px;">
        <div v-for="(chat, index) in finalChat" :key="index" class="message-group">
          <div class="user-message">
            <el-avatar size="small" icon="el-icon-user" class="message-avatar"></el-avatar>
            <el-card class="message-card" shadow="hover">
              <div class="message-content">{{ chat.user }}</div>
            </el-card>
          </div>
          <div class="ai-message">
            <el-avatar size="small" icon="el-icon-s-robot" class="message-avatar"></el-avatar>
            <el-card class="message-card ai-card" shadow="hover">
              <div class="message-content" v-html="chat.ai"></div>
            </el-card>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <el-row :gutter="20" class="input-row">
        <el-col :span="18">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="userInput"
            maxlength="500"
            show-word-limit
            :autosize="{ minRows: 3, maxRows: 6 }"
            resize="none"
            class="chat-input"
          />
        </el-col>
        <el-col :span="6">
          <el-button
            @click="start"
            type="primary"
            class="send-button"
            :loading="loading"
            :disabled="!userInput.trim()"
          >
            {{ loading ? 'AI思考中...' : '发送' }}
            <i class="el-icon-send" v-if="!loading"></i>
            <i class="el-icon-loading is-spinning" v-else></i>
          </el-button>
        </el-col>
      </el-row>
    </div>
  </div>
</template>
import CryptoJS from 'crypto-js'
<script>
import CryptoJS from 'crypto-js';
export default {
  name: "OptimizedChat",
  data() {
    return {
      appId: '724ffa67',
      status: 'init',
      ttsWS: null,
      totalRes: '',
      userInput: '',
      aiContentRequest: '',
      finalChat: [],
      loading: false
    };
  },
  methods: {
    getWebsocketUrl() {
      return new Promise((resolve, reject) => {
        const apiKey = '63d3ad2339fd9a36d797cc0eb2692818';
        const apiSecret = 'MDNkNTJhZTcwZWJjYjFkMDliYWY0MTYz';
        const url = 'ws://spark-openapi.cn-huabei-1.xf-yun.com/v1/assistants/uf6murctcnhm_v1';
        const host = window.location.host;
        const date = new Date().toGMTString();
        const algorithm = 'hmac-sha256';
        const headers = 'host date request-line';
        const signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v1.1/chat HTTP/1.1`;
        const signatureSha = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
        const signature = CryptoJS.enc.Base64.stringify(signatureSha);
        const authorizationOrigin = `api_key="${apiKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
        const authorization = window.btoa(authorizationOrigin);
        const finalUrl = `${url}?authorization=${authorization}&date=${date}&host=${host}`;
        console.log(finalUrl);
        resolve(finalUrl);
      });
    },
    setStatus(status) {
      this.status = status;
    },
    connectWebSocket() {
      this.setStatus('ttsing');
      this.getWebsocketUrl().then((url) => {
        let ttsWS;
        if ('WebSocket' in window) {
          ttsWS = new WebSocket(url);
        } else if ('MozWebSocket' in window) {
          ttsWS = new MozWebSocket(url);
        } else {
          alert('浏览器不支持WebSocket');
          return;
        }
        this.ttsWS = ttsWS;
        ttsWS.onopen = (e) => {
          this.webSocketSend();
        };
        ttsWS.onmessage = (e) => {
          this.result(e.data);
        };
        ttsWS.onerror = (e) => {
          clearTimeout(this.playTimeout);
          this.setStatus('error');
          alert('WebSocket报错，请F12查看详情');
          console.error(`详情查看：${encodeURI(url.replace('wss:', 'https:'))}`);
        };
        ttsWS.onclose = (e) => {
          console.log(e);
        };
      });
    },
    webSocketSend() {
      let that = this;
      const params = {
        header: {
          app_id: this.appId,
          uid: '随意',
        },
        parameter: {
          chat: {
            domain: 'lite',
            temperature: 0.5,
            max_tokens: 1024,
          },
        },
        payload: {
          message: {
            text: [
              {"role": "user", "content": that.userInput}
            ]
          },
        },
      };
      console.log(JSON.stringify(params));
      this.ttsWS.send(JSON.stringify(params));
    },
    start() {
      this.loading = true;
      const userMessage = this.userInput.trim();
      if (!userMessage) {
        this.loading = false;
        return;
      }

      // 添加到聊天记录并初始化AI回答
      this.finalChat.push({ user: userMessage, ai: '' });

      // 滚动到最新消息
      this.$nextTick(() => {
        this.scrollToBottom();
      });

      this.totalRes = '';
      this.aiContentRequest = '';
      this.connectWebSocket();
    },
    scrollToBottom() {
      const chatMessages = document.querySelector('.chat-messages');
      if (chatMessages) {
        chatMessages.scrollTop = chatMessages.scrollHeight;
      }
    },
    requestHandle(requestData) {
      this.aiContentRequest = this.aiContentRequest + requestData.payload.choices.text[0].content;
    },
    result(resultData) {
      let jsonData = JSON.parse(resultData);
      this.totalRes += resultData;
      this.userInput = ""
      if (jsonData.header.code === 0) {
        // 获取当前对话的最后一个条目
        const currentChat = this.finalChat[this.finalChat.length - 1];
        // 提取当前返回的文本片段
        const content = jsonData.payload.choices.text[0].content;
        // 实时追加到AI回答中
        currentChat.ai += content;

        // 滚动到最新消息
        this.scrollToBottom();

        if (jsonData.header.status === 2) {
          // 完成态处理：关闭连接并结束加载
          this.ttsWS.close();
          this.loading = false;
        }
      } else {
        // 错误处理
        alert(`提问失败: ${jsonData.header.code}:${jsonData.header.message}`);
        console.error(`${jsonData.header.code}:${jsonData.header.message}`);
        this.loading = false;
      }
    },
  },
};
</script>

<style scoped>
.chat-container {
  max-width: 1200px;
  margin: 30px auto;
}

.chat-wrapper {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.chat-messages {
  background-color: #f9f9f9;
  border-bottom: 1px solid #ebeef5;
}

.message-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  animation: fadeIn 0.3s ease-in-out;
}

.user-message, .ai-message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
}

.message-avatar {
  margin: 0 10px;
}

.message-card {
  max-width: 80%;
  border-radius: 8px;
  border: none;
  box-shadow: none;
  margin: 0;
}

.user-message .message-card {
  background-color: #e6f7ff;
  border-radius: 8px 8px 8px 0;
  order: 2;
}

.ai-message .message-card {
  background-color: #fff;
  border-radius: 8px 8px 0 8px;
  order: 1;
}

.message-content {
  padding: 12px;
  word-break: break-word;
  font-size: 14px;
  line-height: 1.5;
}

.input-row {
  padding: 10px 15px;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
}

.chat-input {
  height: auto;
  border-radius: 8px;
  box-shadow: none;
  border: 1px solid #dcdfe6;
}

.chat-input:focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.send-button {
  width: 100%;
  height: 74px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border-radius: 8px;
  transition: all 0.2s;
}

.send-button:hover {
  background-color: #3a8ee6;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>
